import os
from PIL import Image, ImageDraw, ImageFont


def add_water(image, text, fontsize):
    # 字体文件
    font = ImageFont.truetype("f001.ttf", fontsize)

    # 添加背景
    new_img = Image.new("RGBA", (image.size[0] * 3, image.size[1] * 3), (255, 255, 255, 255))
    new_img.paste(image, image.size)

    # 添加水印
    font_len = len(text)
    rgba_image = new_img.convert("RGBA")
    text_overlay = Image.new("RGBA", rgba_image.size, (0, 0, 0, 0))
    image_draw = ImageDraw.Draw(text_overlay)

    # 水印数量
    for i in range(0, rgba_image.size[0], font_len * 40 + 300):
        for j in range(0, rgba_image.size[1], 300):
            # print(f'i:{i}, j:{j}, text:{text}, font:{font}')
            image_draw.text((i, j), text, font=font, fill=(0, 0, 0, 20))

    # 水印文字角度
    text_overlay = text_overlay.rotate(45)
    image_with_text = Image.alpha_composite(rgba_image, text_overlay)

    image_with_text = image_with_text.crop((image.size[0], image.size[1], image.size[0] * 2, image.size[1] * 2))
    return image_with_text


if __name__ == "__main__":
    text = "link与门"  # 水印文字
    fontsize = 50  # 文字大小
    base_path = r"D:\吉他谱\guitai pro\gp\Funkyman\edbl Kazuki Isogai - Surface\img"
    for root, files, dirs in os.walk(base_path):
        for dir in dirs:
            path = os.path.join(root, dir)
            filename = path.split("\\")[-1]
            dir_water = f"{base_path}_water"
            if not os.path.exists(dir_water):
                os.mkdir(dir_water)
            water_file = f"{dir_water}\\{filename}"

            if path.find("_water") == -1:
                print(filename)
                img = Image.open(path)
                fill_img = add_water(img, text, fontsize)
                # 一定要保存为png格式
                fill_img.save(water_file)
